package com.quan.common.core.support;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import com.quan.common.base.exception.TimeOutException;
import com.quan.common.base.exception.UnauthorizedException;
import com.quan.common.base.pojo.JSONResult;
import com.quan.common.utils.WebUtils;

public class BaseController {

	protected Logger logger = LoggerFactory.getLogger(this.getClass());

	@Autowired
	protected HttpServletRequest request;

	@Autowired
	protected HttpServletResponse response;

	@ExceptionHandler(Exception.class)
	@ResponseBody
	public Object handleControllerException(HttpServletRequest request, HttpServletResponse response, Throwable e) {
		// 处理Ajax请求异常
		
		if (e instanceof TimeOutException) { //未登录或登录超时412
			// 返回JSON格式数据
			return JSONResult.errorException(HttpStatus.PRECONDITION_FAILED.value(), e.getMessage());
			
		} else if (e instanceof UnauthorizedException) {// 没有权限403
			// 返回JSON格式数据
			return JSONResult.errorException(HttpStatus.FORBIDDEN.value(), e.getMessage());
			
		} else {
			// 返回JSON格式数据
			return JSONResult.errorException(WebUtils.getStatus(request).value(), e.getMessage());
		}
	}

}
